package fr.mywiki.business.search;

import java.rmi.RemoteException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;

import javax.ejb.FinderException;

import fr.mywiki.business.entry.EntryLite;
import fr.mywiki.business.utils.StringUtils;
import fr.mywiki.model.ejbAdapter.DataController;
import fr.mywiki.model.ejbAdapter.EntityHomeCache;
import fr.mywiki.model.ejbAdapter.Value;
import fr.mywiki.model.ejbAdapter.entity.EntryLocal;
import fr.mywiki.model.queries.QueriesFacade;

/**
 * This manager contains several methods which deal with entry research.
 * 
 * @author tlombard
 */
public class SearchEntryManager {
	private SearchEntryManager() {}

	/**
	 * Searches the entry whose identifier is given in parameter.
	 * 
	 * @param id a <code>Long</code> object.
	 * @return a <code>Collection</code> object containing the <code>EntryLite</code> object
	 *         corresponding to this search or a empty collection.
	 * @throws RemoteException if an exception was thrown while accessing the database.
	 */
	public static Collection searchById(Long id) throws RemoteException {
		Collection result = new ArrayList();
		Value value = DataController.getValue(id, EntryLite.TYPE_ENT);
		if (value != null)
			result.add(value);
		return result;
	}

	/**
	 * Searches the entries whose title corresponds to the one given in parameter. The title of an
	 * entry corresponds to <code>title</code> if and only if the intern title of the entry is
	 * equivalent to the intern writing of <code>title</code>.
	 * 
	 * @param title the <code>String</code> object to search.
	 * @return a <code>Collection</code> object containing the <code>EntryLite</code> objects
	 */
	public static Collection searchByTitle(String title) throws SQLException {
		return QueriesFacade.searchEntryByTitle(title);
	}
	
	/**
	 * <p>
	 * Searches and returns the only entry whose intern title corresponds to
	 * the intern form of the title given in parameter.
	 * </p>
	 * <p>
	 * If none can be found, the concerned entry is considered as not existent
	 * and null is returned.
	 * </p>
	 * 
	 * @param title the title of the searched entry.
	 * @return a <code>EntryLite</code> object or null
	 */
	public static EntryLite searchExactTitle(String title) {
		String internTitle = StringUtils.getInternForm(title);

		Collection col = null;
		try {
			col = EntityHomeCache.getInstance().getEntryHome()
					.findByInternTitle(internTitle);
		} catch (FinderException e) {
			return null;
		}
		if(col.isEmpty())
			return null;
		
		return ((EntryLocal) ((ArrayList) col).get(0)).getEntryLite();
	}
}
